//still to be edited, pero nakapagsearch na :)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.Properties;
import java.util.*;

public class SearchBookTitle
{
    /* the default framework is embedded*/
    private String framework = "embedded";
    private String driver = "com.mysql.jdbc.Driver";
    private String protocol = "jdbc:mysql://localhost/";
    public String[][] result;

    public String[] attributes;
    public int rowSize;
    public int colSize;

	public SearchBookTitle(String keyword)
	{
		go(keyword);
	}


    void go(String keyword)
    {

        /* load the desired JDBC driver */
        loadDriver();
		Connection conn = null;
	    ArrayList statements = new ArrayList(); // list of Statements, PreparedStatements
		Statement s = null;
		ResultSet rs = null;

        try
        {
            Properties props = new Properties(); // connection properties
            // providing a user name and password is optional in the embedded
            // and derbyclient frameworks
            props.put("user", "root");
            props.put("password", "root");

            String dbName = "library"; // the name of the database

            conn = DriverManager.getConnection(protocol + dbName, props);

            conn.setAutoCommit(false);

			s = conn.createStatement();
	        statements.add(s);

	        StringTokenizer st = new StringTokenizer(keyword);
	        while(st.hasMoreTokens())
	        {
	        	String temp = st.nextToken();
		        rs = s.executeQuery("SELECT * FROM Book WHERE title LIKE '%" + temp + "%'");
		        rowSize = 0;
				while(rs.next())
				{
					rowSize++;
				}
				colSize = 8;
				result = new String[rowSize][colSize];
				attributes = new String[colSize];
				attributes[0] = "id";
				attributes[3] = "isbn";
				attributes[1] = "status";
				attributes[2] = "publisher";
				attributes[4] = "title";
				attributes[5] = "author";
				attributes[6] = "year_pub";
				attributes[7] = "date_acq";


				int ind = 0;

				rs = s.executeQuery("SELECT * FROM Book WHERE title LIKE '%" + temp + "%'");

				while(rs.next())
				{
					result[ind][0] =  rs.getString("id");
					result[ind][3] = rs.getString("isbn");
					result[ind][1] = rs.getString("status");
					result[ind][2] = rs.getString("publisher");
					result[ind][4] = rs.getString("title");
					result[ind][5] = rs.getString("author");
					result[ind][6] = rs.getString("year_pub");
					result[ind][7] = rs.getString("date_acq");
                                        ind++;
				}

                                System.out.println(result[ind-1][4]);
                                
			}

            conn.commit();

        }
        catch (SQLException sqle)
        {
            printSQLException(sqle);
        } finally {

            // Statements and PreparedStatements
            int i = 0;
            while (!statements.isEmpty()) {
                // PreparedStatement extend Statement
                Statement st = (Statement)statements.remove(i);
                try {
                    if (st != null) {
                        st.close();
                        st = null;
                    }
                } catch (SQLException sqle) {
                    printSQLException(sqle);
                }
            }

            //Connection
            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            } catch (SQLException sqle) {
                printSQLException(sqle);
            }
        }
    }

    private void loadDriver() {
        /*
         *  The JDBC driver is loaded by loading its class.
         *  If you are using JDBC 4.0 (Java SE 6) or newer, JDBC drivers may
         *  be automatically loaded, making this code optional.
         *
         *  In an embedded environment, this will also start up the Derby
         *  engine (though not any databases), since it is not already
         *  running. In a client environment, the Derby engine is being run
         *  by the network server framework.
         *
         *  In an embedded environment, any static Derby system properties
         *  must be set before loading the driver to take effect.
         */
        try {
            Class.forName(driver).newInstance();
            System.out.println("Loaded the appropriate driver");
        } catch (ClassNotFoundException cnfe) {
            System.err.println("\nUnable to load the JDBC driver " + driver);
            System.err.println("Please check your CLASSPATH.");
            cnfe.printStackTrace(System.err);
        } catch (InstantiationException ie) {
            System.err.println(
                        "\nUnable to instantiate the JDBC driver " + driver);
            ie.printStackTrace(System.err);
        } catch (IllegalAccessException iae) {
            System.err.println(
                        "\nNot allowed to access the JDBC driver " + driver);
            iae.printStackTrace(System.err);
        }
    }

    /**
     * Reports a data verification failure to System.err with the given message.
     *
     * @param message A message describing what failed.
     */
    private void reportFailure(String message) {
        System.err.println("\nData verification failed:");
        System.err.println('\t' + message);
    }

    /**
     * Prints details of an SQLException chain to <code>System.err</code>.
     * Details included are SQL State, Error code, Exception message.
     *
     * @param e the SQLException from which to print details.
     */
    public static void printSQLException(SQLException e)
    {
        // Unwraps the entire exception chain to unveil the real cause of the
        // Exception.
        while (e != null)
        {
            System.err.println("\n----- SQLException -----");
            System.err.println("  SQL State:  " + e.getSQLState());
            System.err.println("  Error Code: " + e.getErrorCode());
            System.err.println("  Message:    " + e.getMessage());
            // for stack traces, refer to derby.log or uncomment this:
            //e.printStackTrace(System.err);
            e = e.getNextException();
        }
    }

    public static void main(String args[]){
		/*Scanner sc = new Scanner(System.in);
		String params = new String();

		params = sc.next();*/

		SearchBookTitle seabkti = new SearchBookTitle("Ring");
    }

}
